package org.go.smart.temperature;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class WeeklyScheduler {
	
	private PeriodsContainer periodsContainer = new PeriodsContainer();
	
	public Double getWantedTemperature() {
		return periodsContainer.getWantedTemperature();
	}
	
	public void clean() {
		this.periodsContainer = new PeriodsContainer();
	}
	
	public void addPeriod(final int startDay, final int endDay, final int startHour, final int endHour, final int startMinute, 
			final int endMinute, double wantedTemp) {
		periodsContainer.addPeriod(startDay, endDay, startHour, endHour, startMinute, endMinute, wantedTemp);
	}

}

class PeriodsContainer {
	List<Period> periods = new ArrayList<>();
	
	public void addPeriod(final int startDay, final int endDay, final int startHour, final int endHour, final int startMinute, 
			final int endMinute, double wantedTemp) {
		Period period = new Period(startDay, endDay, startHour, endHour, startMinute, endMinute, wantedTemp);
		if (!periodConflictsWithAnother(period)) {
			periods.add(period);
		}
		
	}

	private boolean periodConflictsWithAnother(Period period) {
		for (Period currentPeriod : periods) {
			if (period.periodIsConflicting(currentPeriod)) {
				return true;
			}
		}
		return false;
	}
	
	public Double getWantedTemperature() {
		for (Period period : periods) {
			if (period.containsCurrentDate()) {
				return period.wantedTemp;
			}
		}
		return null;
	}
}

class Period {
	int startDay;

	int endDay;
	int startHour;
	int endHour;
	int startMinute;
	int endMinute;
	
	double wantedTemp;
	
	public Period(int startDay, int endDay, int startHour, int endHour,
			int startMinute, int endMinute, double wantedTemp) {
		super();
		this.startDay = startDay;
		this.endDay = endDay;
		this.startHour = startHour;
		this.endHour = endHour;
		this.startMinute = startMinute;
		this.endMinute = endMinute;
		this.wantedTemp = wantedTemp;
	}
	
	public boolean periodIsConflicting(final Period period) {
		if ((period.startDay < endDay && period.startHour < endHour && period.startMinute < endMinute) ||
				(startDay < period.endDay && startHour < period.endHour && startMinute < period.endMinute)){
			return true;
		}
		return false;
	}
	
	public boolean containsCurrentDate() {
		Calendar date = Calendar.getInstance();
		int day = date.get(Calendar.DAY_OF_WEEK);
		int hour = date.get(Calendar.HOUR_OF_DAY);
		int minute = date.get(Calendar.MINUTE);
		
		if (day >= this.startDay && day <= this.endDay && hour >= this.startHour && hour <= this.endHour && minute >= this.startMinute &&
				minute <= this.endMinute) {
			return true;
		}
		
		return false;
	}
	
}
